package com.ct.ecommerce.framework.security;

import com.ct.ecommerce.framework.constant.SecurityConstants;
import java.util.HashMap;
import java.util.Map;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

/**
 * JWT内容增强器
 * @author changtong
 * @since 2021/5/29
 */
public class JwtTokenEnhancer implements TokenEnhancer {

  private static final String ID = "id";

  @Override
  public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    UserWrapperDTO userPrincipal = (UserWrapperDTO) authentication.getPrincipal();
    Map<String, Object> info = new HashMap<>();
    // 把用户ID设置到JWT中
    info.put(SecurityConstants.ID_FIELD, userPrincipal.getUserId().toString());
    ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(info);
    return accessToken;
  }
}